package util;

import java.sql.*;

public class JdbcUtils {

    private static String url = "jdbc:mysql://localhost:3306/itcast";
    private static String rootname = "root";
    private static String password = "296924";
    private static Connection conn = null;
    private static ResultSet rs = null;
    private static PreparedStatement pstmt = null;

    /**
     * 数据库连接
     *
     * @throws SQLException
     */
    public static Connection dbconn() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, rootname, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 增加数据库信息和修改信息和修改信息
     *
     * @param sql
     * @return
     */
    public static int addsql(String sql) {
        int i = 0;
        try {
            pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            i = pstmt.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        closeconn(null, pstmt, null);
        return i;
    }

    /**
     * 查找数据库信息
     *
     * @param sql
     * @return
     */
    public static ResultSet selectsql(String sql) {
        try {
            pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            rs = pstmt.executeQuery(sql);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 关闭数据库，释放资源
     */
    public static void closeconn(ResultSet rs, Statement pstmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

